﻿using System;
using System.Threading;
using System.Windows.Forms;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;
using Microsoft.WindowsMobile.Status;
using PowerAwareBluetooth.Controller.Manager;

namespace PowerAwareBluetooth.Model
{
    /// <summary>
    /// Represent the bluetooth device
    /// </summary>
    public class BluetoothAdapter
    {

        #region Members

        IManager m_IManager;

        /// <summary>
        /// InTheHand.Net bluetooth client
        /// </summary>
        BluetoothClient m_client;
        
        /// <summary>
        /// InTheHand.Net bluetooth Radio
        /// </summary>
        BluetoothRadio m_radio;
        
        /// <summary>
        /// Registry entry - the entry where the current bluetooth radio mode is saved
        /// </summary>
       //RegistryState m_registryState;

        //private static SystemState m_systemState = new SystemState(SystemProperty.BluetoothStatePowerOn);

        #endregion Members

        #region Methods
        
        /// <summary>
        /// creates the adapter and registers to blue-tooth events on the cellphone
        /// </summary>
        public BluetoothAdapter(IManager manager)
        {
            m_IManager = manager;
            m_client = new BluetoothClient();
            m_radio = BluetoothRadio.PrimaryRadio;
        }

        /// <summary>
        /// 1. activate bluetooth
        /// 2. search for other bluetooth devices
        /// 3. return bluetooth to previous mode
        /// </summary>
        /// <returns>true if other bluetooth devices are in range</returns>
        public bool SampleForOtherBluetooth()
        {
            //remember bluetooth last mode of operation
            RadioMode last_mode = m_radio.Mode;
            
            //1.
            m_radio.Mode = RadioMode.Discoverable;
            
            //2.
            bool res = IsOtherBluetoothExist();

            //3.
            m_radio.Mode = last_mode;
            
            return res;
        }
        
      

        /// <summary>
        /// Property for bluetooth radio mode
        /// </summary>
        public RadioMode RadioMode
        {
            get
            {
                int maxRetries = 60;
                
                // the loop was added because when the cell phone opens
                // the bluetooth is still not ready and an exception is raised.
                // we assume that after one minute (60 seconds) the bluetooth
                // is available.

                while (true)
                {
                    try
                    {
                        if (m_radio != null)
                        {
                            return m_radio.Mode;
                        }
                        else
                        {
                            return RadioMode.PowerOff;
                        }
                    }
                    catch (Exception e)
                    {
                        if (maxRetries > 0)
                        {
                            Thread.Sleep(1000);
                            maxRetries--;
                            continue;
                        }
                        MessageBox.Show(e.StackTrace, e.Message);
                        throw;
                    }

                }

            }
            set
            {
                if (m_radio != null)
                {
                    m_radio.Mode = value;
                }
                
                
            }
        }

    
        /// <summary>
        /// Is bluetooth device picking up another device signal and is this device a paired device
        /// </summary>
        /// <returns></returns>
        private bool IsOtherBluetoothExist()
        {
            //find all paired device (last parameter = true tells function to retrieve all devices in range).
            BluetoothDeviceInfo[] btInfoInRange = m_client.DiscoverDevices(10, false, false, false, true);
            //get all paired device
            BluetoothDeviceInfo[] btInfoPaired = m_client.DiscoverDevices(10, true, false, false);
         
            //iterate on all devices in range and see if any of them is a paired device
            foreach (BluetoothDeviceInfo deviceInRange in btInfoInRange)
            {
                foreach (BluetoothDeviceInfo pairedDevice in btInfoPaired)
                {
                    if (!Closing)
                    {
                        if (deviceInRange.DeviceName == pairedDevice.DeviceName)
                        {
                            return true;
                        }
                    }
                    else
                    {
                        // when closing - reffer to as no other bluetooth exists
                        return false;
                    }
                }
            }


            return false;
        }

        #endregion Methods


        private bool Closing
        {
            get
            {
                return (m_IManager != null && m_IManager.Closing);
            }
        }
    }

    public delegate void BluetoothRadioModeChangedHandler();
}
